<template>
  <a-drawer v-model:visible="visible" title="门闸控制" placement="right" :width="450" :destroyOnClose="true">
    <a-form ref="formRef" :model="model" :rules="rules" :label-col="{ span: 7 }" @finish="onFinish">
      <!-- <a-form-item label="门闸名称" name="entranceName">
        {{ model.entranceName }}
      </a-form-item> -->
      <a-form-item label="门闸开关状态" name="entranceState">
        {{ model.entranceState === 0 ? '关' : '开' }}
      </a-form-item>
      <a-form-item label="视频播放">
        <a-spin :spinning="loading" tip="视频加载中...">
          <video id="video" :src="videoUrl" controls autoplay></video>
        </a-spin>
      </a-form-item>
      <a-form-item label="操作">
        <a-button @click="handleControl(1)">开门</a-button>
        <a-divider type="vertical" />
        <a-button type="primary" @click="handleControl(3)">暂停</a-button>
        <a-divider type="vertical" />
        <a-button type="primary" @click="handleControl(2)">关门</a-button>
      </a-form-item>
    </a-form>
    <CommonAMap ref="commonAMap" @oks="getMapData" />
  </a-drawer>
</template>

<script lang="ts">
import { watch, ref, nextTick, defineComponent, getCurrentInstance } from 'vue';
import { JDictSelectTag } from '/@/components/Form';
import { controlApi, entranceInfoApi } from '/@/api/gate';
import { projectListApi } from '@/api/project';
import CommonAMap from '/@/components/CommonAMap/index.vue';
import { useUserStore } from '/@/store/modules/user';
import { deviceCameraPlayApi } from '/@/api/camera/play';
import Plyr from 'plyr';
import 'plyr/dist/plyr.css';
export default defineComponent({
  components: { JDictSelectTag, CommonAMap },
  setup(_, { emit }) {
    const userStore = useUserStore();
    let player: any = null;
    let { proxy } = getCurrentInstance();
    let visible = ref(false);
    let loading = ref(false);
    let model = ref({
      entranceName: '',
      entranceState: '',
      entranceCode: '',
    });
    let videoUrl = ref('');
    let regionList = ref([]);
    let rules = ref({
      name: [{ required: true, message: '请输入站点名称' }],
      contect: [{ required: true, message: '请输入联系人' }],
      stationSubtype: [{ required: true, message: '请选择站点主体类型' }],
      stationType: [{ required: true, message: '请选择站点类型' }],
      tel: [{ required: true, message: '请输入电话' }],
      mn: [{ required: true, message: '请输入设备编码' }],
      regionCode: [{ required: true, message: '请选择所在镇街' }],
    });

    let projectList = ref([]);

    function getRegionData(data: []) {
      regionList.value = data;
    }

    /**
     * 初始化数据
     * @param {number} id
     */
    function init(id) {
      videoUrl.value = '';
      entranceInfoApi({ id }).then((res) => {
        let { camInfo } = res;
        if (camInfo) {
          let [deviceId, channelId] = camInfo.split('+');
          playVideo({ deviceId, channelId });
        }
        model.value = { ...res };
      });
    }

    /**
     * 播放视频
     */
    function playVideo(data: any) {
      loading.value = true;
      deviceCameraPlayApi(data).then((res) => {
        loading.value = false;
        videoUrl.value = res.fmp4;
        let node = document.getElementById('video');
        player = new Plyr(node, {
          controls: ['play-large', 'play', 'fullscreen'],
        });
      });
    }

    function resetForm() {
      proxy.$refs.formRef.resetFields();
    }

    /**
     * 初始化项目列表
     */
    function initProjectList() {
      projectListApi({}).then((res) => {
        projectList.value = res;
      });
    }

    function onFinish() {
      let data = {
        ...model.value,
      };
      if (!data['id']) {
        stationAddApi(data).then((res) => {
          proxy.$refs.formRef.resetFields();
          visible.value = false;
          userStore.setRequestStation();
          emit('oks');
        });
      } else {
        stationModifyApi(data).then((res) => {
          proxy.$refs.formRef.resetFields();
          visible.value = false;
          userStore.setRequestStation();
          emit('oks');
        });
      }
    }

    function handleControl(controlTo: number) {
      controlApi({ entranceCode: model.value.entranceCode, controlTo }).then((res) => {
        emit('oks');
      });
    }

    /**
     * 打开地图
     */
    function openMap() {
      proxy.$refs.commonAMap.visible = true;
      nextTick(() => {
        proxy.$refs.commonAMap.initMap(model.value);
      });
    }

    watch(
      () => visible.value,
      (v) => {
        if (v) {
          initProjectList();
        }
        if (!v) {
          delete model.value.id;
          destroyVideo(document.getElementById('video'));
          model.value = {
            // 名称
            name: '',
            // 地址
            address: '',
            // 联系人
            contect: '',
            // 经度
            longitue: 0,
            // 纬度
            latitude: 0,
            // 站点编码
            stationCode: '',
            // 站点主体类型
            stationSubtype: '',
            // 站点类型
            stationType: '',
            // 电话号码
            tel: '',
          };
        }
      },
      { deep: true }
    );

    function destroyVideo(videoElement) {
      // 停止视频播放
      videoElement.pause();

      // 尝试释放内存，对于某些浏览器，设置src为空字符串会释放内存
      videoElement.removeAttribute('src'); // 移除src
      videoElement.load(); // 重新加载视频元素

      // 销毁组件
      if (player) {
        player.destroy();
      }

      // 从DOM中移除视频元素
      // if (videoElement.parentNode) {
      //   videoElement.parentNode.removeChild(videoElement);
      // }
    }

    /**
     * 获取地图返回的经纬度
     */
    function getMapData({ longitue, latitude }) {
      Object.assign(model.value, {
        longitue,
        latitude,
      });
      AMap.plugin('AMap.Geocoder', () => {
        new AMap.Geocoder().getAddress([longitue, latitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            model.value.address = result.regeocode.formattedAddress;
          }
        });
      });
    }

    return {
      init,
      visible,
      model,
      rules,
      projectList,
      regionList,
      videoUrl,
      loading,
      resetForm,
      onFinish,
      openMap,
      getMapData,
      getRegionData,
      handleControl,
    };
  },
});
</script>